package com.wkck.interceptor;

import com.wkck.constant.JwtClaimsConstant;
import com.wkck.context.BaseContext;
import com.wkck.properties.JwtProperties;
import com.wkck.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: CK
 * @Date: 2024/02/23/14:38
 * @Description:
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        String userToken = request.getHeader(jwtProperties.getUserTokenName());

        try {
            log.info("开始进行令牌校验: {}", userToken);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), userToken);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户Id: {}" ,userId);
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception exception) {
            response.setStatus(401);
            log.error("令牌校验失败: {}", userToken);
            return false;
        }
    }
}
